<script setup>

import { getCategoryByType } from '@/api/category.js'
import { getSnacksPage, snacksStatusByStatus,deleteSnacks } from '@/api/snacks.js'
import { useRouter } from 'vue-router'
import { onMounted, ref } from 'vue'
import { ElMessageBox} from 'element-plus'
const router = useRouter()

const tableData = ref([]) //零食数据
const page = ref(1) //页数
const pageSize = ref(10) //每页数
const total = ref(0) // 零食列表的总条目数量
const name = ref('') //零食名称
const snacksCategoryList = ref([]) //零食分类列表
const categoryId = ref('') //分类id
const status = ref('') //起售状态
const loading = ref(false)
const isSearch = ref(false)

const selectedItems = ref([])// 存储选中的条目
const statustype = [
  {
    value: 0,
    label: '停售'
  },
  {
    value: 1,
    label: '启售'
  }
]

onMounted(() => {
  getSnacksCategoryList()
  init()
})

//分页查询
const init = async () => {
  loading.value = true
  const params = {
    name: name.value,
    page: page.value,
    pageSize: pageSize.value,
    status: status.value,
    categoryId: categoryId.value
  }
  const res = await getSnacksPage(params)
  if (res.data.code === 1) {
    tableData.value = res.data.data.records
    total.value = res.data.data.total
  }
  loading.value = false
}

//获取零食分类列表
const getSnacksCategoryList = async () => {
  const res = await getCategoryByType({ type: 1 })
  if (res.data.code === 1) {
    snacksCategoryList.value = res.data.data
  }
}

//添加零食
const addSnacks = st => {
  if (st === 'add') {
    router.push('/snacks/add')
  }
}

//设置每页多少条
const handleSizeChange = val => {
  pageSize.value = val
  init()
}

//设置当前页
const handleCurrentChange = val => {
  page.value = val
  init()
}

//修改零食停售起售
const statusHandle = async row => {
  //  console.log( row)
  const params = {
    id: row.id,
    status: !row.status ? 1 : 0
  }
  await ElMessageBox.confirm('你确认修改当前零食状态吗', '温馨提示', {
    type: 'warning',
    confirmButtonText: '确认',
    cancelButtonText: '取消'
  })
  const res = await snacksStatusByStatus(params)
  //  console.log(res)
  if (res.data.code === 1) {
    ElMessage.success('零食状态修改成功！')
    init()
  }
}

//修改零食
const addSnackstype = id => {
  router.push({ path: '/snacks/add', query: { id } })
}

//当选择项发生变化时会触发该事件
const handleSelectionChange = (selection) => {
  selectedItems.value = selection.map(item => item.id).join(',') //后端需要的是字符串
  console.log(selectedItems.value);
}


const deleteHandle = async (type, id) => {
  if (type === '单删') {
    await ElMessageBox.confirm('你确认删除零食吗', '温馨提示', {
      type: 'warning',
      confirmButtonText: '确认',
      cancelButtonText: '取消'
    });
      const res = await deleteSnacks(id)
      if(res.data.code === 1){
      ElMessage.success('删除成功');
      init();
      }
  } else {
    if (selectedItems.value.length === 0) {
      ElMessage.warning('请先选择要删除的零食');
      return;
    }
    await ElMessageBox.confirm('你确认删除选中的零食吗？', '温馨提示', {
      type: 'warning',
      confirmButtonText: '确认',
      cancelButtonText: '取消'
    });
   
      // 调用删除多个条目 selectedItems 数组
      const res = await deleteSnacks(selectedItems.value)
      if(res.data.code ===1 ){
      ElMessage.success('删除成功');
      init();
      }
  }
}

</script>
<template>
  <div class="dashboard-container">
    <div class="container">
      <div class="tableBar" style="display: inline-block; width: 100%">

        <label style="margin-right: 10px">零食名称：</label>
        <el-input v-model="name" placeholder="请填写零食名称" style="width: 15%" clearable @clear="init()" @keyup.enter.native="init()" />

        <label style="margin-right: 5px; margin-left: 20px">零食分类：</label>
        <el-select v-model="categoryId" placeholder="请选择" clearable style="width: 15%" @clear="init()">
          <el-option v-for="(item, index)  in snacksCategoryList" :key="index" :label="item.name" :value="item.id" />
        </el-select>

        <label style="margin-right: 5px; margin-left: 20px">起售状态：</label>
        <el-select v-model="status" placeholder="请选择" clearable style="width: 15%" @clear="init()">
          <el-option v-for="item in statustype" :key="item.value" :label="item.label" :value="item.value" />
        </el-select>

        <el-button class="normal-btn continue" @click="init()">
          查询
        </el-button>

        <div style="float: right">
          <el-button type="danger" round @click="deleteHandle('批量')">
            批量删除
          </el-button>
          <el-button type="primary" round style="margin-left:20px" @click="addSnacks('add')">
            + 新增零食
          </el-button>
        </div>
      </div>

      <el-table v-loading="loading" :data="tableData" stripe class="tableBox" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="25" />
        <el-table-column prop="name" label="零食名称" />
        <el-table-column prop="image" label="图片">
          <template #default="scope">
            <el-image style="width: 80px; height: 40px; border: none; cursor: pointer" :src="scope.row.image">
              <div slot="error" class="image-slot">
                <img src="./../../assets/noImg.png" style="width: auto; height: 40px; border: none">
              </div>
            </el-image>
          </template>
        </el-table-column>
        <el-table-column prop="categoryName" label="零食分类" />
        <el-table-column label="售价">
          <template #default="scope">
            <span style="margin-right: 10px">￥{{ (scope.row.price ).toFixed(2)*100/100 }}</span>
          </template>
        </el-table-column>
        <el-table-column label="售卖状态">
          <template #default="scope">
            <div class="tableColumn-status" :class="{ 'stop-use': String(scope.row.status) === '0' }">
              {{ String(scope.row.status) === '0' ? '停售' : '启售' }}

            </div>
          </template>
        </el-table-column>
        <el-table-column prop="updateTime" label="最后操作时间" />
        <el-table-column label="操作" width="250" align="center">
          <template #default="scope">
            <el-button type="text" size="small" class="blueBug" @click="addSnackstype(scope.row.id)">
              修改
            </el-button>
            <el-button type="text" size="small" class="delBut" @click="deleteHandle('单删', scope.row.id)">
              删除
            </el-button>
            <el-button type="text" size="small" class="non" :class="{
                         blueBug: scope.row.status == '0',
                         delBut: scope.row.status != '0'
                       }" @click="statusHandle(scope.row)">
              {{ scope.row.status == '0' ? '启售' : '停售' }}

            </el-button>
          </template>

        </el-table-column>

      </el-table>
      <div class="demo-pagination-block">

        <el-pagination :current-page="page" :page-size="pageSize" :page-sizes="[2, 4, 10, 40]" :background="background" layout="total, sizes, prev, pager, next, jumper," :total="total" @size-change="handleSizeChange" @current-change="handleCurrentChange" prev-text="上一页" next-text="下一页" />

      </div>

    </div>
  </div>

</template>

<style lang="scss" scoped>
.dashboard {
  &-container {
    margin: 10px;

    .container {
      background: #fff;
      position: relative;
      z-index: 1;
      padding: 30px 28px;
      border-radius: 4px;
      .tableBar {
        display: flex;
        margin-bottom: 20px;
        justify-content: space-between;
      }

      .tableBox {
        width: 100%;

        border-bottom: 0;

        .tableColumn-status {
          display: flex;
          align-items: center;
        }
      }

      .tableColumn-status::before {
        width: 5px;
        height: 5px;
        background: #1dc779;
        border-radius: 50%;
        content: '';
        display: inline-block;
        margin-right: 6px;
      }

      .stop-use::before {
        background-color: #bdbdbd;
      }

      .non::after {
        display: none;
      }

      div:focus {
        outline: none;
      }

      .blueBug {
        color: #419eff !important;
        position: relative;
      }

      .blueBug::after {
        content: '';
        position: absolute;
        right: -6px;
        height: 14px;
        width: 0px;
        border-right: solid 1px #ebeef5 !important;
      }

      .delBut {
        color: #f56c6c !important;
        position: relative;
      }

      .delBut::after {
        content: '';
        position: absolute;
        right: -6px;
        height: 14px;
        width: 0px;
        border-right: solid 1px #ebeef5 !important;
      }

      .pageList {
        text-align: center;
        margin-top: 30px;
      }

      .normal-btn {
        background: #1a89b9;
        color: white;
        margin-left: 20px;
      }

      .demo-pagination-block {
        margin-top: 30px;
        float: right;
      }
    }
  }
}
</style>